package com.token.iot.bratterycharging.gateway.sender;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.outstanding.framework.core.Logger;
import com.outstanding.framework.core.PendingException;
import com.outstanding.framework.log.LoggerFactory;
import com.outstanding.framework.utils.Base64;
import com.token.iot.bratterycharging.gateway.AbstractSender;
import com.token.iot.bratterycharging.gateway.ChannelHandlerContextManager;
import com.token.iot.bratterycharging.gateway.IDGeneration;
import com.token.iot.bratterycharging.gateway.Semaphore;
import com.token.iot.bratterycharging.gateway.SemaphoreManager;
import com.token.iot.bratterycharging.gateway.Sender;
import com.token.iot.bratterycharging.gateway.utils.ByteUtil;

import io.netty.channel.ChannelHandlerContext;

/**
 * 获取固件说明
 * 
 * @author chenzhixuan
 *
 */
@Component("AAESender")
public class AAESender extends AbstractSender {

	private static ChannelHandlerContextManager manager = new ChannelHandlerContextManager();

	private static Logger loger = LoggerFactory.getLogger(AAESender.class);
	
	
	
	@Override
	public Object send(String imei, Map<String, String> params) throws PendingException {
		 //查找对应的HandlerContext
		ChannelHandlerContext context = manager.getChannelHandlerContextByImei(imei);
		String sessionid = IDGeneration.createSeesionID();
		String command =code+sessionid+"/";
		byte[] c = ByteUtil.addFlag(command.getBytes());
		context.writeAndFlush(c);
		String key = imei+"@"+sessionid;
		//信号量
		Semaphore semaphore = SemaphoreManager.registerCommand(key, this);
		try {
			semaphore.await();
		} catch (InterruptedException e) {
			loger.error(e);
		}
		//得到回复
		String response =  semaphore.getResponse();
		byte[] r = response.getBytes();
		
		byte[] bs = new byte[r.length-14];
		System.arraycopy(r, 13, bs, 0, r.length-14);
		String remark = Base64.encode(bs);
		return remark;
	}
	


}
